//
//  Observable+HandyJSON.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/11.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import UIKit
import RxSwift
import Moya
import HandyJSON

/// 数据 转 模型
extension ObservableType where E == Response {
    public func mapHandyJsonModel<T: HandyJSON>(_ url: String, _ type: T.Type) -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(response.mapHandyJsonModel(url, T.self))
        }
    }
}
/// 数据 转 模型
extension Response {
    func mapHandyJsonModel<T: HandyJSON>(_ url: String, _ type: T.Type) -> T {
        let jsonString = String.init(data: data, encoding: .utf8)
        UserDefaults.standard.set(data, forKey: url + SYUserInfo.strand.userId)
        let dic: Dictionary = (jsonString?.getDictionaryFromJSONString())!
        var code:String = ""
        if let c = dic["code"] as? Int {
            code = "\(c)"
        } else if let s = dic["code"] as? String {
            code = s
        }
        let infoDic: [String: String] = ["code": code, "message": (dic["message"] as? String) ?? ""]
        UserDefaults.standard.set(infoDic, forKey: url + SYUserInfo.strand.userId + REQUEST_DIC)
        print("返回值：\n", dic.showJsonString)
        if let modelT = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
            return modelT
        }
        //        return JSONDeserializer<T>.deserializeFrom(json: "{\"msg\":\"\("common.try".L())\"}")!
        return JSONDeserializer<T>.deserializeFrom(json: "{\"msg\":\"\("common.try" )\"}")!
    }
}

